from django.shortcuts import render
from django.views.generic import View, TemplateView
from django.http.response import JsonResponse,HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse

# Create your views here.
class BaseView(View):
    def get(self, request):
        return render(request, 'base.html')


# 基础View类视图
# class IndexView(View):
#     def get(self, request):
#         hosts_count = 10
#         return render(request, 'index.html',locals())

# 高级视图类 TemplateView
class IndexView(LoginRequiredMixin, TemplateView):
    template_name = 'index.html'

    # 传输数据
    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['hosts_count'] = 20
        return context


class LoginView(TemplateView):
    template_name = 'login.html'

    def post(self, request):
        # print(request.POST)
        # 接收用户数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 判断
        # 如果验证成功 就会返回user对象
        user = authenticate(username=username, password=password)
        if user:
            # if username == 'admin' and password == '123456':
            # 响应处理  json格式
            # 登录操作
            login(request, user)
            res = {'status': 0, 'msg': '登录成功'}
        else:
            res = {'status': 1, 'msg': '登录失败'}
        return JsonResponse(res)

class LogoutView(View):
    def get(self,request):
        logout(request)
        return HttpResponseRedirect(reverse('user_login'))